package com.xique.blelock.view.DeviceManager;

import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.support.annotation.Nullable;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.TextView;

import com.alibaba.fastjson.JSON;
import com.clj.fastble.data.BleDevice;
import com.clj.fastble.utils.HexUtil;
import com.ivin.crop.Log;
import com.ivin.refreshlayout.QRefreshLayout;
import com.ivin.refreshlayout.RefreshHandler;
import com.ivin.widget.ScrollViewTricksOfMore;
import com.xique.blelock.Adapter.RecordAdapter;
import com.xique.blelock.Interface.BleConnectListen;
import com.xique.blelock.Interface.BleListenData;
import com.xique.blelock.Interface.BleNotificationListen;
import com.xique.blelock.NetUtils.NetResult;
import com.xique.blelock.NetUtils.XqNetClient;
import com.xique.blelock.R;
import com.xique.blelock.Utils.ACache;
import com.xique.blelock.Utils.BleUtils;
import com.xique.blelock.Utils.CommUtil;
import com.xique.blelock.Utils.Stringkey;
import com.xique.blelock.Utils.TimeUtil;
import com.xique.blelock.model.LockAllinfo;
import com.xique.blelock.model.LockStatus;
import com.xique.blelock.model.NormalOpenMode;
import com.xique.blelock.model.OpenResult;
import com.xique.blelock.model.Operationinfo;
import com.xique.blelock.model.UserOfLockinfo;
import com.xique.blelock.view.AcountManager.FingerListActivty;
import com.xique.blelock.view.AcountManager.QuickSettingActivty;
import com.xique.blelock.view.AcountManager.UserListActivity;
import com.xique.blelock.view.BaseActivity;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.Collections;
import java.util.Date;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import jsc.kit.datetimepicker.widget.DateTimePicker;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

import static com.xique.blelock.Utils.Stringkey.Dayindex;
import static com.xique.blelock.Utils.Stringkey.FIRST_FIG_INDEX;
import static com.xique.blelock.Utils.Stringkey.FIRST_METHOD_INDEX;
import static com.xique.blelock.Utils.Stringkey.FIRST_RESULT_INDEX;
import static com.xique.blelock.Utils.Stringkey.FIRST_TIME_INDEX;
import static com.xique.blelock.Utils.Stringkey.Hand_response_ok;
import static com.xique.blelock.Utils.Stringkey.Hourindex;
import static com.xique.blelock.Utils.Stringkey.Minuteindex;
import static com.xique.blelock.Utils.Stringkey.Monthindex;
import static com.xique.blelock.Utils.Stringkey.RECORD_FRAME_LENGTH;
import static com.xique.blelock.Utils.Stringkey.SecondIndex;
import static com.xique.blelock.Utils.Stringkey.Yearhightindex;
import static com.xique.blelock.Utils.Stringkey.Yearlowindex;
import static com.xique.blelock.Utils.Stringkey.commopenindex;
import static com.xique.blelock.Utils.Stringkey.hardinfolength;
import static com.xique.blelock.Utils.Stringkey.lockstatusindex;
import static com.xique.blelock.Utils.Stringkey.managerorderindex;
import static com.xique.blelock.Utils.Stringkey.volumindex;

/**
 * Created by Administrator on 2018/12/7.
 */

public class DeviceControllerActivity extends BaseActivity implements BleListenData, BleConnectListen, BleNotificationListen {

//    @BindView(R.id.qmuitop)
//    QMUITopBarLayout qmuiTopBarLayout;

    @BindView(R.id.openlock)
    ImageButton openlock;

    @BindView(R.id.openlocrecordlistview)
    RecyclerView recyclerView;

    @BindView(R.id.selectData)
    ImageView selectDateview;

    @BindView(R.id.refleshbtnloading)
    View refleshloadding;

    @BindView(R.id.refleshbtn)
    ImageView refleshbtn;

    @BindView(R.id.refreshLayout)
    QRefreshLayout refreshLayout;

    @BindView(R.id.scrollviewid)
    ScrollViewTricksOfMore scrollViewTricksOfMore;


    RecordAdapter recordAdapter;
    //当前设备
    private BleDevice bleDevice;

    private LockAllinfo lockAllinfo;

    private List<Operationinfo> operationinfoList = new ArrayList<>();

    private int index_read = 0;

    private int total_count;
    private int indexlast_freshLayout1 = 0;

    @BindView(R.id.title)
    TextView titile;

    @BindView(R.id.rightimage)
    ImageView rightimage;

    private static final int NextPageReq = 10001;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.controllerlayout);
        ButterKnife.bind(this);


        initView();
        BleUtils.setBleDevice(bleDevice);
        BleUtils.setBleNotificationListen(this);
        BleUtils.setBleListen(this);
        BleUtils.setNofifyCation();

//        getOperationList();
        //读取设备的握手信息
        showProgressDialog();
    }

    @Override
    protected void onResume() {
        super.onResume();
        BleUtils.setBleListen(this);
        BleUtils.setConnectListen(this);
        BleUtils.setBleNotificationListen(this);

        LockAllinfo  templock = (LockAllinfo) ACache.get(this).getAsObject(Stringkey.lockAllinfo);
        if(templock != null){
            lockAllinfo = templock;
        }
    }

    @Override
    protected void initView() {
        super.initView();

        bleDevice = getIntent().getParcelableExtra(Stringkey.DeviceInfo);
        titile.setText(bleDevice.getName());
        rightimage.setVisibility(View.VISIBLE);
        rightimage.setImageResource(R.drawable.quicksetting);

        recyclerView.setLayoutManager(new LinearLayoutManager(this));
        recyclerView.setHasFixedSize(true);
        recyclerView.setNestedScrollingEnabled(false);


        recordAdapter = new RecordAdapter(operationinfoList);
        recyclerView.setAdapter(recordAdapter);
//        recyclerView.setHasFixedSize(true);
//        recyclerView.setNestedScrollingEnabled(false);
        refreshLayout.setRefreshMode(QRefreshLayout.RefreshMode.FROM_BOTTOM);
        refreshLayout.setScrollUpChild(recyclerView);

        refreshLayout.setRefreshHandler(new RefreshHandler() {
            @Override
            public void onRefresh(QRefreshLayout refresh) {
                Log.e("准备加载："+indexlast_freshLayout1 +"页", "");
            }

            @Override
            public void onLoadMore(QRefreshLayout refresh) {
                    //准备刷新更火的数据
//                indexlast_freshLayout1++;
                Log.e("准备加载："+indexlast_freshLayout1 +"页", "");
                        if(operationinfoList.size() == 0){
                            refreshLayout.loadMoreComplete();
                            showToast(DeviceControllerActivity.this, "暂时没有记录");
                            return;
                        }else{

                            getOperationList(operationinfoList.get(operationinfoList.size()-1).getTime(), false);
                        }

            }
        });
    }

    @Override
    protected void onDestroy() {
        ACache.get(this).remove(Stringkey.lockAllinfo);
        super.onDestroy();



    }



    @OnClick(R.id.openlock)
    public void openLock(){
        if(lockAllinfo.getLockStatus() == LockStatus.closestatus)
        {
            sendDat(Stringkey.openlockdata);
        }else{
            sendDat(Stringkey.closelockdata);
        }

    }

    @OnClick(R.id.BACKER)
    public void BackLastPage(){
        finish();
    }

    //跳转到便捷操作界面
    @OnClick(R.id.rightimage)
    public void  jumpQuickSetting(){
        Intent intent = new Intent(DeviceControllerActivity.this, QuickSettingActivty.class);
        ACache.get(this).put(Stringkey.lockAllinfo, lockAllinfo);
                startActivity(intent);
    }


    @OnClick({R.id.zhiwenlist, R.id.userlist, R.id.shebeiinfo})
    public void Onclick(View view){
        ACache.get(this).put(Stringkey.lockAllinfo, lockAllinfo);
        if(view.getId() == R.id.zhiwenlist){
            Intent intent = new Intent(this, FingerListActivty.class);
            startActivity(intent);

        }else  if(view.getId() == R.id.userlist){
            Intent intent = new Intent(this, UserListActivity.class);
            startActivity(intent);

        }else if(view.getId() == R.id.shebeiinfo){
            Intent intent = new Intent(this, DeviceInfoActivty.class);
            startActivity(intent);
        }
    }

    private void getOperationList(String time, final boolean search) {
        XqNetClient netClient =  new XqNetClient();
        JSONObject jsonobject = new JSONObject();

        try {
            jsonobject.put("token", userInfo.getToken());
            jsonobject.put("uid", userInfo.getUid());
            jsonobject.put("lockId", BleUtils.getBleDevice().getMac().replace(":", ""));//E0:4C:63:6D:82:43
            jsonobject.put("timestamp", TimeUtil.getSystemCurrentTimeLong()+"");

            jsonobject.put("startTime", time);
            jsonobject.put("total", 10);
        } catch (JSONException e) {
            e.printStackTrace();
        }

        showProgressDialog();
        netClient.queryLockRecords(jsonobject.toString()).enqueue(new Callback<NetResult<List<Operationinfo>>>() {//获取验证码
            @Override
            public void onResponse(Call<NetResult<List<Operationinfo>>> call, Response<NetResult<List<Operationinfo>>> response) {


                if(response.body().isSuccess()){
                    List<Operationinfo> fingerInfos = response.body().getData();
                    Log.e("获取操作记录=== "+ JSON.toJSONString(fingerInfos), "");
                    if(fingerInfos!= null){
                        if(search){
                            operationinfoList.clear();
                        }
                        operationinfoList.addAll(fingerInfos);
                        Collections.sort(operationinfoList);
                        CommUtil.searchName(operationinfoList, lockAllinfo);
                        lockAllinfo.setLockRecords(operationinfoList);
                        recordAdapter.setDeviceList(operationinfoList);
                        recordAdapter.notifyDataSetChanged();


                    }else{
                        showToast(DeviceControllerActivity.this, "没有数据啦");
                    }
                    refreshLayout.loadMoreComplete();


                }else {
                    showToast(DeviceControllerActivity.this, "没有获取到开锁记录 ");
                }
                hideProgressDialog();
            }

            @Override
            public void onFailure(Call<NetResult<List<Operationinfo>>> call, Throwable t) {
                t.printStackTrace();
                hideProgressDialog();

            }
        });

    }


    private List<Operationinfo> lockRecords = new ArrayList<>();
    private void addOperate(){

        XqNetClient netClient =  new XqNetClient();
        JSONObject jsonobject = new JSONObject();

        try {
            jsonobject.put("token", userInfo.getToken());
            jsonobject.put("uid", userInfo.getUid());
            jsonobject.put("lockId", BleUtils.getBleDevice().getMac().replace(":", ""));//E0:4C:63:6D:82:43
            jsonobject.put("timestamp", TimeUtil.getSystemCurrentTimeLong()+"");
            jsonobject.put("lockRecords", com.alibaba.fastjson.JSONObject.toJSONString(lockRecords));
        } catch (JSONException e) {
            e.printStackTrace();
        }

        Log.e("上报操作记录----："+ jsonobject.toString(), "");
        showProgressDialog();
        netClient.addLockRecords(jsonobject.toString()).enqueue(new Callback<NetResult>() {//获取验证码
            @Override
            public void onResponse(Call<NetResult> call, Response<NetResult> response) {

                //Log.e("添加操作记录=== "+ response, "");
                if(response.body().isSuccess()){
                    lockRecords.clear();
                    operationinfoList.clear();
                    getOperationList(TimeUtil.getSystemCurrentTimeLong()/1000+"", false);
                    showToast(DeviceControllerActivity.this, "同步记录成功");
                }else {
                    showToast(DeviceControllerActivity.this, "没有获取到开锁记录 ");
                }
                hideProgressDialog();
            }

            @Override
            public void onFailure(Call<NetResult> call, Throwable t) {
                t.printStackTrace();
                hideProgressDialog();

            }
        });

    }



    //开锁 关锁
    private void sendDat(String strdat){

        BleUtils.sendData(HexUtil.hexStringToBytes(Stringkey.openlockdata + getMyOder()));
    }

    private String getMyOder(){

        UserOfLockinfo userOfLockinfo = new UserOfLockinfo();
        userOfLockinfo.setUid(userInfo.getUid());
        int index = lockAllinfo.getLockBandUserList().indexOf(userOfLockinfo);
        userOfLockinfo = lockAllinfo.getLockBandUserList().get(index);
        String appid = HexUtil.encodeHexStr(new byte[]{(byte) userOfLockinfo.getOrder()});
        return appid;
    }


    //从设备端获取 记录的总条数
    @OnClick(R.id.refleshbtn)
    public void reFleshRecord(){
        refleshbtn.setVisibility(View.GONE);
        refleshloadding.setVisibility(View.VISIBLE);
        scrollViewTricksOfMore.setEnabled(false);
        BleUtils.sendData(Stringkey.getOprationRecord);
    }
    @OnClick(R.id.selectData)
    public void selectDate(){
        showDateDialog();
    }

    //连上设备读取设备信息
    private void StartHand(){
        showProgressDialog();
        BleUtils.sendData(Stringkey.readDeviceinfo );
    }

    //指定读取某一条记录
    private void readRecord(int index){
        BleUtils.sendData(Stringkey.Read_RecordHead + HexUtil.encodeHexStr(new byte[]{(byte) index}));
    }

    @Override
    public void didReciveData(byte[] data) {
        String rep = HexUtil.encodeHexStr(data);
        if(rep.equals(Stringkey.lock_status_open)){
            showToast(DeviceControllerActivity.this, "已经开锁");
            openlock.setBackground(getResources().getDrawable(R.drawable.closelockstyle));
            lockAllinfo.setLockStatus(1);
        }

        if(rep.equals(Stringkey.lock_status_close)){
            showToast(DeviceControllerActivity.this, "已经关锁");
            lockAllinfo.setLockStatus(2);
            openlock.setBackground(getResources().getDrawable(R.drawable.openlockstyle));
        }


        //判断是否为同步开锁记录
        if(rep.startsWith(Stringkey.getOprationRecord)){
            //
            total_count = (0xff&data[2])+ (0xff&data[3])*256;
            if(total_count > 0 && (index_read==0)){
                index_read = 1;
                readRecord(index_read);
            }else if(total_count == 0){
                refleshloadding.setVisibility(View.GONE);
                refleshbtn.setVisibility(View.VISIBLE);
                scrollViewTricksOfMore.setEnabled(true);
                showToast(DeviceControllerActivity.this, "暂时没有记录");
                return;
            }

        }

        if(rep.startsWith(Stringkey.Read_RecordHead)){//开始读取记录
            //取出当前是第几条
            final int currentindex  = (0xff&data[2])+ (0xff&data[3])*256;

            //提交记录到服务器
//            lockRecords
            Operationinfo operationinfo = new Operationinfo();
            operationinfo.setMode(data[FIRST_METHOD_INDEX]);
            operationinfo.setOrder(data[FIRST_FIG_INDEX]);
            operationinfo.setResult(data[FIRST_RESULT_INDEX]==0x55? OpenResult.FAILED: OpenResult.SUCCESS);
            operationinfo.setUid(userInfo.getUid());
            operationinfo.setTime((long)(data[FIRST_TIME_INDEX]&0xff) +(0xff&data[FIRST_TIME_INDEX+1])*256 + (long)(0xff&data[FIRST_TIME_INDEX+2])*256*256 + (long)(0xff&data[FIRST_TIME_INDEX+3])*256*256*256 + "");

            String timestr = operationinfo.getTime();
            long tiemtemp  = Long.parseLong(timestr) & 0xffffffff;

            if(Long.toHexString(tiemtemp).equalsIgnoreCase("ffffffff")){//数据属于非法
                showToast(DeviceControllerActivity.this, "同步到非法数据:--操作记录数据不正确");
                index_read = 0;
                new Handler().postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        BleUtils.sendData(Stringkey.clearRecord);//清楚错误数据
                    }
                }, 200);

                return;
            }

            lockRecords.add(operationinfo);
            if(currentindex*2 <= total_count) {
                Operationinfo operationinfo2 = new Operationinfo();
                operationinfo2.setMode(data[FIRST_METHOD_INDEX + RECORD_FRAME_LENGTH]);
                operationinfo2.setOrder(data[FIRST_FIG_INDEX  + RECORD_FRAME_LENGTH]);
                operationinfo2.setResult(data[FIRST_RESULT_INDEX + RECORD_FRAME_LENGTH] == 0x55 ? OpenResult.FAILED: OpenResult.SUCCESS);
                operationinfo2.setUid(userInfo.getUid());
                operationinfo2.setTime((data[FIRST_TIME_INDEX + RECORD_FRAME_LENGTH]&0xff) + (0xff&data[FIRST_TIME_INDEX + 1 + RECORD_FRAME_LENGTH]) * 256 + (long) (0xff&data[FIRST_TIME_INDEX + 2 + RECORD_FRAME_LENGTH]) * 256 * 256 + (long) (0xff&data[FIRST_TIME_INDEX + 3 + RECORD_FRAME_LENGTH]) * 256 * 256 * 256 + "");
                lockRecords.add(operationinfo2);
                //这里判断试下是否还需要继续读取

            }
            if(currentindex*2 < total_count){
                readRecord(currentindex+1);
            }else
            {
                BleUtils.sendData(Stringkey.clearRecord);
            }

        }

        if(rep.startsWith(Stringkey.readDeviceinfo)){
            if(data.length == hardinfolength){
                //存储当前锁的副管理员
                lockAllinfo.setSecondorder(data[managerorderindex]^(byte)0xAA);
                Log.e("当前的负管理员是："+lockAllinfo.getSecondorder(), "");
                //读取当前状态
                lockAllinfo.setLockStatus(data[lockstatusindex]);
                //更新锁的状态 1表示打开， 2表示关闭,上锁了
                if(lockAllinfo.getLockStatus() == 2){
                    openlock.setBackground(getResources().getDrawable(R.drawable.openlockstyle));
                }else{
                    openlock.setBackground(getResources().getDrawable(R.drawable.closelockstyle));
                }

                //读取当前的电量数据
                lockAllinfo.setLockPower(data[volumindex]+"");



                //读取当前设备的便捷开锁配置
                Boolean temp = (Boolean) ACache.get(this).getAsObject(Stringkey.fast_open_prefix + BleUtils.getBleDevice().getMac().replace(":",""));
                if(temp != null)
                {
                    lockAllinfo.setIsfastopen(temp);
                }
                lockAllinfo.setIsusualopen(data[commopenindex]  == NormalOpenMode.openstatus?true:false);

                //把当前最新的数据推送到服务器
                updateLockInfo();
                ACache.get(this).put(Stringkey.lockAllinfo, lockAllinfo);

                new Handler().postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        //发送敞开模式
                        if(lockAllinfo.isIsfastopen()) {
                            BleUtils.sendData(Stringkey.openlockdata);
                       }
                    }
                }, 300);


            }

            //这里需要同时时间给设备
            //Date mDate = new Date();
            Calendar calendar  = Calendar.getInstance();
            int year = calendar.get(Calendar.YEAR);
            int month = calendar.get(Calendar.MONTH);
            int days = calendar.get(Calendar.DAY_OF_MONTH);
            int hour = calendar.get(Calendar.HOUR_OF_DAY);
            int minite = calendar.get(Calendar.MINUTE);
            int second  = calendar.get(Calendar.SECOND);

            // 03 01
            byte[] settimedat = new byte[9];
            settimedat[0] = 3;
            settimedat[1] = 1;
            settimedat[Yearlowindex] = (byte) (year%256);
            settimedat[Yearhightindex] = (byte) (year/256);
            settimedat[Monthindex] = (byte) month;
            settimedat[Dayindex] = (byte)days;
            settimedat [Hourindex] = (byte)hour;
            settimedat[Minuteindex] = (byte)minite;
            settimedat[SecondIndex] = (byte)second;
            BleUtils.sendData(settimedat);
            //初始化结束
            hideProgressDialog();
        }

        if(rep.startsWith(Stringkey.clearRecord)){
            refleshloadding.setVisibility(View.GONE);
            refleshbtn.setVisibility(View.VISIBLE);
            scrollViewTricksOfMore.setEnabled(true);
            index_read = 0;
            //判断当前是否有数据需要推送服务器
            if(lockRecords.size()> 0){
                addOperate();
            }
//            getOperationList(TimeUtil.getSystemCurrentTimeLong()+"");//同步完成重新刷洗一下listview
        }

        //如果长开模式响应，那么就判端当前是否需要使用便捷开锁模式
        if(rep.startsWith(Stringkey.comm_open_rep_prefix)){
            if(lockAllinfo.isIsfastopen()){
                new Handler().postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        BleUtils.sendData(Stringkey.openlockdata);
                    }
                }, 100);

            }
        }

        //如果握手成功
        if(rep.startsWith(Hand_response_ok)){
            hideProgressDialog();// 等待握手成功
            queryLockInfo();
        }




    }


    //查询大年设备和用户之间的关系
    private void queryLockInfo(){

        XqNetClient netClient =  new XqNetClient();
        JSONObject jsonobject = new JSONObject();

        try {
            jsonobject.put("token", userInfo.getToken());
            jsonobject.put("uid", userInfo.getUid());
            jsonobject.put("lockId", BleUtils.getBleDevice().getMac().replace(":", ""));//E0:4C:63:6D:82:43
            jsonobject.put("timestamp", TimeUtil.getSystemCurrentTimeLong()+"");

        } catch (JSONException e) {
            e.printStackTrace();
        }

        showProgressDialog();
        netClient.queryLockInfo(jsonobject.toString()).enqueue(new Callback<NetResult<LockAllinfo>>() {//
            @Override
            public void onResponse(Call<NetResult<LockAllinfo>> call, Response<NetResult<LockAllinfo>> response) {
                hideProgressDialog();
                if(response.body().isSuccess()){
                    lockAllinfo = response.body().getData();
                    Log.e("获取到的锁所有的信息是："+ JSON.toJSONString(lockAllinfo), "");

                        operationinfoList.addAll(lockAllinfo.getLockRecords());
                        Collections.sort(operationinfoList);
                        CommUtil.searchName(operationinfoList, lockAllinfo);
                        recordAdapter.setDeviceList(operationinfoList);
                        recordAdapter.notifyDataSetChanged();
                        //更新当前用户对锁的控制权限
                        UserOfLockinfo user = new UserOfLockinfo();
                        user.setUid(userInfo.getUid());
                        int index = lockAllinfo.getLockBandUserList().indexOf(user);
                        user = lockAllinfo.getLockBandUserList().get(index);
                        lockAllinfo.setRole(user.getRole());
                        if(user.getRole() == 0 || (user.getRole() ==1)){
                            lockAllinfo.setIsmanager(true);
                        }

                    //从设备端读取锁的状态
                    StartHand();

                }else {
                    showToast(DeviceControllerActivity.this, "没有获取到开锁记录 ");
                }

            }

            @Override
            public void onFailure(Call<NetResult<LockAllinfo>> call, Throwable t) {
                t.printStackTrace();


            }
        });
    }

    //更新设备信息 updateLockInfo
    private void updateLockInfo(){

        XqNetClient netClient =  new XqNetClient();
        JSONObject jsonobject = new JSONObject();

        try {
            jsonobject.put("token", userInfo.getToken());
            jsonobject.put("uid", userInfo.getUid());
            jsonobject.put("lockId", lockAllinfo.getLockId());//E0:4C:63:6D:82:43
            jsonobject.put(Stringkey.hardwareVersion, lockAllinfo.getHardwareVersion());
            jsonobject.put(Stringkey.softwareVersion, lockAllinfo.getSoftwareVersion());
            jsonobject.put(Stringkey.Vendor, lockAllinfo.getVendor());
            jsonobject.put(Stringkey.serialNuber, lockAllinfo.getSerialNumber());
            jsonobject.put(Stringkey.lockPower, lockAllinfo.getLockPower());
            jsonobject.put(Stringkey.LockName, lockAllinfo.getLockName());
            jsonobject.put(Stringkey.lockStatus, lockAllinfo.getLockStatus());
            jsonobject.put("timestamp", TimeUtil.getSystemCurrentTimeLong()+"");

        } catch (JSONException e) {
            e.printStackTrace();
        }

        showProgressDialog();
        netClient.updateLockInfo(jsonobject.toString()).enqueue(new Callback<NetResult>() {//
            @Override
            public void onResponse(Call<NetResult> call, Response<NetResult> response) {
                Log.e("更新设备信息："+ JSON.toJSONString(response.body()), "");
                if(response.body().isSuccess()){


                }else {
                    showToast(DeviceControllerActivity.this, "更新设备信息失败 "+response.body().getMessage());
                }
                hideProgressDialog();
            }

            @Override
            public void onFailure(Call<NetResult> call, Throwable t) {
                t.printStackTrace();
                hideProgressDialog();

            }
        });
    }


    private void showDateDialog() {
        Calendar calendar = Calendar.getInstance();
        calendar.set(Calendar.YEAR, 2000);
        calendar.set(Calendar.MONTH, 0);
        calendar.set(Calendar.DAY_OF_MONTH, 1);
        calendar.set(Calendar.HOUR_OF_DAY, 0);
        calendar.set(Calendar.MINUTE, 0);
        Date startDate = calendar.getTime();

        calendar.set(Calendar.YEAR, 2099);
        calendar.set(Calendar.MONTH, 0);
        calendar.set(Calendar.DAY_OF_MONTH, 1);
        calendar.set(Calendar.HOUR_OF_DAY, 0);
        calendar.set(Calendar.MINUTE, 0);
        Date endDate = calendar.getTime();

        //方式一：构建自己的builder
        DateTimePicker.Builder TBuilder = new DateTimePicker.Builder(this)
                .setTitle("")
                .setCancelTextColor(getResources().getColor(R.color.colorBlue))
                .setOkTextColor(getResources().getColor(R.color.colorBlue))
                .setTitleTextColor(0xFF999999)
                .setSelectedTextColor(getResources().getColor(R.color.colorBlack))
                .setKeepLastSelected(true)
                .setShowYMDHMLabel(true)
                .setShowType(DateTimePicker.ShowType.DAY);
        DateTimePicker dateTimePicker1 = new DateTimePicker(this, new DateTimePicker.ResultHandler() {
            @Override
            public void handle(Date date) {
                Log.e("当前时间是："+date.toString(), "");
                queryLockRecordsByTime(date.getTime()/1000+"");

            }
        }, startDate, endDate, TBuilder);
        dateTimePicker1.show(new Date());
    }

    //查询某一天的操作记录queryLockRecordsByTime
    private void queryLockRecordsByTime(String time) {
        XqNetClient netClient =  new XqNetClient();
        JSONObject jsonobject = new JSONObject();

        try {
            jsonobject.put("token", userInfo.getToken());
            jsonobject.put("uid", userInfo.getUid());
            jsonobject.put("lockId", BleUtils.getBleDevice().getMac().replace(":", ""));//E0:4C:63:6D:82:43
            jsonobject.put("timestamp", TimeUtil.getSystemCurrentTimeLong()+"");

            jsonobject.put(Stringkey.StartTime, time);
            jsonobject.put(Stringkey.EndtTime, Long.parseLong(time)+24*60*60);
        } catch (JSONException e) {
            e.printStackTrace();
        }

        showProgressDialog();
        netClient.queryLockRecordsByTime(jsonobject.toString()).enqueue(new Callback<NetResult<List<Operationinfo>>>() {//获取验证码
            @Override
            public void onResponse(Call<NetResult<List<Operationinfo>>> call, Response<NetResult<List<Operationinfo>>> response) {


                if(response.body().isSuccess()){
                    List<Operationinfo> fingerInfos = response.body().getData();
                    Log.e("当天的操作记录=== "+ JSON.toJSONString(fingerInfos), "");
                    if(fingerInfos!= null){
                        operationinfoList.clear();

                        operationinfoList.addAll(fingerInfos);
                        Collections.sort(operationinfoList);
                        CommUtil.searchName(operationinfoList, lockAllinfo);
                        lockAllinfo.setLockRecords(operationinfoList);
                        recordAdapter.setDeviceList(operationinfoList);
                        recordAdapter.notifyDataSetChanged();


                    }else{
                        showToast(DeviceControllerActivity.this, "没有数据啦");
                    }
                    refreshLayout.loadMoreComplete();


                }else {
                    showToast(DeviceControllerActivity.this, "没有获取到开锁记录 ");
                }
                hideProgressDialog();
            }

            @Override
            public void onFailure(Call<NetResult<List<Operationinfo>>> call, Throwable t) {
                t.printStackTrace();
                hideProgressDialog();

            }
        });

    }



    @Override
    public void didConnetced(BleDevice bleDevice) {

    }

    @Override
    public void didDisConnect(BleDevice bleDevice) {
            finish();
    }



    @Override
    public void didNotification(BleDevice bleDevice, boolean result) {
        //读取设备的握手信息
        hideProgressDialog();
        if(!result){
            showToast(this, "蓝牙通知设置失败");
            finish();
        }else{
//            queryLockInfo();
            //发起握手
            showProgressDialog();
            new Handler().postDelayed(new Runnable() {
                @Override
                public void run() {
                    BleUtils.sendData(Stringkey.HandCmd);
                }
            }, 400);

        }

    }
}
